<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <GroupTabs ref="groupTabs" :api="getEnvList" v-model:value="env" @select="handleSelect" />
    <BasicTable @register="registerTable" class="overflow-hidden">
      <template #toolbar>
        <Authority :value="'confgroup.add'">
          <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        </Authority>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'confgroup.edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              auth: 'confgroup.del',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]" />
        </template>
      </template>
    </BasicTable>
    <EditDrawer @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getGroupPage, removGroup, getEnvList } from '/@/api/config/group';
import { useDrawer } from '/@/components/Drawer';
import { Authority } from '/@/components/Authority';
import { PageWrapper } from '/@/components/Page';
import EditDrawer from './EditDrawer.vue';
import GroupTabs from '/@/components/GroupTabs'
import GroupTabsActionType from '/@/components/GroupTabs/typing'
import { columns, searchFormSchema } from './data';


const env = ref('Development')
const groupTabs = ref<GroupTabsActionType>()

const [registerDrawer, { openDrawer }] = useDrawer();
const [registerTable, { reload }] = useTable({
  title: '配置分组列表',
  api: getGroupPage,
  immediate: false,
  searchInfo: computed(() => { return { env } }),
  columns,
  formConfig: {
    labelWidth: 90,
    schemas: searchFormSchema,
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 100,
    title: '操作',
    dataIndex: 'action'
  },
});

const handleSelect = async () => {
  await reload()
}

function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
  });
}

async function handleDelete(record: Recordable) {
  await removGroup([record['id']]);
  await handleSuccess()
}

async function handleSuccess() {
  await reload();
  await unref(groupTabs)?.reload()
}
</script>